package softswitch.service;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import softswitch.model.Country;
import softswitch.model.Operator;

@Stateless
public class OperatorDAO {

    @PersistenceContext(unitName = "persistence")
    private EntityManager em;

    public Operator getById(Integer id) {
        return em.find(Operator.class, id);
    }

    public Operator save(Operator operator) {
        em.persist(operator);
        return operator;
    }

    public Operator update(Operator operator) {
        return em.merge(operator);
    }

    public void delete(Integer id) {
        em.remove(em.find(Operator.class, id));
    }

    @SuppressWarnings("unchecked")
    public List<Operator> list(int first, int max) {
        Query query = em.createQuery("SELECT e FROM Operator e");
        if (max > 0) {
            query.setMaxResults(max);
        }
        if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();
    }

    public Operator getByCode(Integer code) {
        Operator result = null;
        Query query = em.createQuery("SELECT e FROM Operator e WHERE e.code=:code");
        query.setParameter("code", code);
        try {
            result = (Operator) query.getSingleResult();
        } catch (Exception e) {
        }
        return result;
    }
    
        public Operator getByNameCountry(String name, Country country) {
        Operator result = null;
        Query query = em.createQuery("SELECT e FROM Operator e WHERE e.name=:name AND e.country = :country");
        query.setParameter("name", name);
         query.setParameter("country", country);
        try {
            result = (Operator) query.getSingleResult();
        } catch (Exception e) {
        }
        return result;
    }

}
